package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.mapper.SellerProductMapper;
import com.example.demo.model.Favorite;
import com.example.demo.model.UserInfo;
import com.example.demo.service.FavoriteService;
import com.example.demo.util.ConstVariable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/favorite")
public class FavoriteController {
    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private SellerProductMapper sellerProductMapper;

    @PostMapping("/add")
    public AjaxResult addFavorite(@RequestParam Integer productId, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        boolean success = favoriteService.addFavorite(userInfo.getId(), productId);
        if (success) {
            sellerProductMapper.updateFavoriteCount(productId, 1);
            return AjaxResult.success("收藏成功");
        }
        return AjaxResult.fail("已经收藏过了");
    }

    @PostMapping("/remove")
    public AjaxResult removeFavorite(@RequestParam Integer productId, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        boolean success = favoriteService.removeFavorite(userInfo.getId(), productId);
        if (success) {
            sellerProductMapper.updateFavoriteCount(productId, -1);
            return AjaxResult.success("取消收藏成功");
        }
        return AjaxResult.fail("取消收藏失败");
    }

    @GetMapping("/list")
    public AjaxResult getFavorites(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        List<Favorite> favorites = favoriteService.getUserFavorites(userInfo.getId());
        return AjaxResult.success(favorites);
    }

    @GetMapping("/check")
    public AjaxResult checkFavorite(@RequestParam Integer productId, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        boolean isFavorite = favoriteService.isFavorite(userInfo.getId(), productId);
        return AjaxResult.success(isFavorite);
    }
} 